/**
 * Created with JetBrains WebStorm.
 * User: ishowshao
 * Date: 13-5-9
 */
var Observable = require('events').EventEmitter;
var User = require('./User');
var OnlineUsers = function () {
    this.users = {};
};
OnlineUsers.prototype = Object.create(Observable.prototype);

/**
 * 添加一个user到在线列表
 * @param {User} user
 */
OnlineUsers.prototype.addUser = function (user) {
    var users = this.users;
    if (!users[user.getId()]) {
        //notify
        users[user.getId()] = user;
        this.emit('user-added', user);
    }
};

OnlineUsers.prototype.removeUser = function (user) {
    var users = this.users;
    var id = user.getId();
    delete users[id];
    this.emit('user-removed', user);
};

/**
 * 获取列表中的user
 * @param id
 * @returns {User|null}
 */
OnlineUsers.prototype.getUserById = function (id) {
    var user = this.users[id] || null;
    if (user && !user.isAlive()) {
        user = null;
    }
    return user;
};

OnlineUsers.prototype.toArray = function () {
    var users = this.users;
    var userArray = [];
    for (var id in users) {
        if (users.hasOwnProperty(id)) {
            userArray.push({
                id: id,
                name: users[id].getName()
            });
        }
    }
    return userArray;
};

module.exports = OnlineUsers;
